<template>
  <div class="mt-1">
    <van-form>
      <van-field
        label="关联单号"
        placeholder="点击此处获取关联单号"
        :value="orderNum"
        is-link
        readonly
        @click="getOrderNum"
      ></van-field>
      <van-field
        v-model="value"
        label="发货工厂"
        readonly
        :value="value"
        placeholder="请选择工厂代码"
      >
      </van-field>
      <!-- 库存状态 -->
      <van-field
        readonly
        label="库存状态"
        :value="kc_value"
        placeholder="请选择库存状态"
      />
      <!-- 退货人 -->
      <!-- <van-field
        v-model="returnPerson"
        label="退货人"
        placeholder="请输入退货人"
      /> -->

      <van-field
        v-model="code"
        clearable
        label="拍码"
        ref="code"
        @focus="focus"
        placeholder="请扫描拍码"
      />
      <ag-grid-vue
        style="width: 100%; height: 50vh"
        class="ag-theme-alpine mt-1"
        :columnDefs="columnDefs"
        :defaultColDef="defaultColDef"
        :gridOptions="gridOptions"
        rowSelection="single"
        :rowData="rowData"
      >
      </ag-grid-vue>
      <van-row type="flex" gutter="30" justify="center">
        <van-col span="7">
          <van-button type="danger" class="mt-1" @click="onRemoveSelected" block
            >删除</van-button
          ></van-col
        >
        <van-col span="7"
          ><van-button type="warning" class="mt-1" @click="updateNum" block
            >修改数量</van-button
          ></van-col
        >
        <van-col span="7"
          ><van-button type="info" class="mt-1" @click="onSubmit" block
            >提交</van-button
          ></van-col
        >
      </van-row>
      <van-popup
        v-model="ShowStatue"
        position="bottom"
        style="height: 100%"
        class="bg-default"
      >
        <show-send-data :ShowDataB="ShowData" @get-val="Sure" />
      </van-popup>
      <van-popup
        v-model="OrderReturnVisible"
        position="bottom"
        style="height: 100%"
        class="bg-default"
      >
        <order-return @close="close" @closetwo="closetwo"></order-return>
      </van-popup>
    </van-form>
    <!-- 修改数量的弹窗提示 -->
    <van-dialog
      v-model="ifShowUpdateNum"
      title="请输入要修改的数量"
      show-cancel-button
      @confirm="SureUpdate"
    >
      <van-field
        v-model="needUpdateNum"
        type="number"
        placeholder="请输入数量"
      />
    </van-dialog>

    <!-- 展示超出库存的物料名称 -->
    <van-dialog v-model="ifShowNoFit" title="退货数量超出库存"> </van-dialog>
  </div>
</template>

<script>
import { AgGridVue } from "ag-grid-vue";
import { parseQRCode, toast } from "../../untils/commion";
import { getDetail, InformationSubmit } from "../../assets/api/post";
import ShowSendData from "../../components/ShowSendDate.vue";
import { AgGrid } from "../../minx/AgGrid";
import OrderReturn from "./OrderReturn.vue";

export default {
  components: { AgGridVue, ShowSendData, OrderReturn },
  mixins: [AgGrid],
  data() {
    return {
      item: "", //存放子项编号
      ifShowNoFit: false,
      returnPerson: "", //退货人
      needUpdateNum: "", //修改后存放数据
      ifShowUpdateNum: false, //修改数量弹窗
      selectDate: [], //选中的行数据
      OrderReturnVisible: false,
      titles: new Map().set(7, "PO退货"),
      type: null,
      value: "",
      sure: false,
      kc_value: "",
      deliveryPlant: "",
      fieldValue: "",
      ShowStatue: false,
      deliveryPlantVisible: false,
      code: "",
      orderNum: "",
      columnDefs: [
        { headerName: "物料", field: "productid", flex: 1.5 },
        { headerName: "拍号", field: "uniqueid", flex: 2 },
        { headerName: "数量", field: "stockquantity", flex: 1.5 },
      ],
      rowData: [],
      detailData: [],
      ShowData: {}, //展示的数据
      stoDate: [], //存放关联单号明细数据
      // 用于验证的数据
      copyTable: [], //复制表格数据
      allName: [], //存放所有的物料号
      noFitWuliao: [], //存放超出数量标准的物料名称
      allDetailWuLiaoCode: [], //存放所有的明细中的物料号
      newitem: "",
    };
  },
  watch: {
    code(newValue) {
      if (this.orderNum) {
        if (newValue.length > 9) {
          let paresqrdata = parseQRCode(newValue);
          if (paresqrdata) {
            if (
              !this.rowData.find((it) => it.uniqueid == paresqrdata.palletNo)
            ) {
              //获取数据
              this.getDetailInfo(paresqrdata.palletNo);
              paresqrdata = "";
              this.code = "";
            } else {
              toast("拍码重复");
              this.code = "";
            }
          } else {
            toast("请检查信息是否完整");
            this.code = "";
          }
        }
      } else {
        toast("请选择关联单号和退货人");
      }
      this.code = "";
    },
  },
  methods: {
    closetwo() {
      this.OrderReturnVisible = false;
      this.rowData = [];
    },
    // 获取焦点时触发的方法
    focus() {
      // 获取焦点时阻止键盘弹出
      this.$refs.code.$refs.input.setAttribute("readonly", "readonly");
      setTimeout(() => {
        this.$refs.code.$refs.input.removeAttribute("readonly");
      }, 200);
    },
    close(val) {
      this.stoDate = val;
      this.allDetailWuLiaoCode = [];
      this.stoDate.forEach((item) => {
        this.allDetailWuLiaoCode.push(item.material);
      });
      this.kc_value =
        this.stoDate[0].stkstatus == "" ? "U" : this.stoDate[0].stkstatus;
      this.orderNum = this.$store.state.purno;
      this.value = this.$store.state.numpo;
      this.$refs.code.focus();
      this.OrderReturnVisible = false;
    },
    setTitle() {
      let res = this.titles.get(this.type);
      this.$store.commit("SET_NAVIGATION", res);
    },
    onFinish({ selectedOptions }) {
      this.deliveryPlantVisible = false;
      this.deliveryPlantAndWarehouse = selectedOptions.map((item) => item.id);
      this.fieldValue = selectedOptions.map((option) => option.name).join("/");
    },
    onRemoveSelected() {
      let selectedData = this.gridApi.getSelectedRows();
      if (this.rowData[0] == null) {
        this.$toast("当前表格为空");
      } else {
        if (selectedData[0] == null) {
          this.$toast("请选择要删除的数据");
        } else {
          this.copyTable.forEach((item) => {
            if (item.materialCode == selectedData[0].productid) {
              item.quantity =
                item.quantity - Number(selectedData[0].stockquantity);
            }
          });
          this.copyTable.forEach((item, index) => {
            if (item.quantity == 0) {
              this.copyTable.splice(index, 1);
            }
          });

          let selctIndex = this.gridApi.applyTransaction({
            remove: selectedData,
          });
          // 删除选中的数据
          this.rowData.splice(selctIndex.remove[0].childIndex, 1);
          this.detailData.splice(selctIndex.remove[0].childIndex, 1);
        }
      }
    },
    getOrderNum() {
      this.OrderReturnVisible = true;
      this.copyTable = [];
      this.detailData = [];
      this.rowData = [];
    },
    //获取后台信息
    async getDetailInfo(val) {
      let res = await getDetail(val);
      if (res.status == 200) {
        this.ShowData = JSON.parse(JSON.stringify(res.data[0]));
        if (this.ShowData) {
          // 校验生产商，供应商，日期是否为空
          if (res.data[0].producerid == null || res.data[0].producerid == "") {
            this.$toast("拍码生产商为空");
            this.code = "";
            return;
          }
          if (res.data[0].supplierid == null || res.data[0].supplierid == "") {
            this.$toast("拍码供应商为空");
            this.code = "";
            return;
          }
          if (this.allDetailWuLiaoCode.indexOf(res.data[0].productid) == -1) {
            this.$toast("订单中无该物料");
            this.code = "";
            return;
          }
          this.ShowStatue = true;
          this.rowData.push(res.data[0]);

          let restwo = {
            materialCode: res.data[0].productid,
            quantity: res.data[0].stockquantity,
          };
          this.allName = [];
          if (this.copyTable[0] == null) {
            this.copyTable.push(restwo);
          } else {
            this.copyTable.forEach((item) => {
              if (restwo.materialCode == item.materialCode) {
                item.quantity += restwo.quantity;
              }
              //存放所有的物料号
              this.allName.push(item.materialCode);
            });
            // 判断如果没有该物料号就添加
            if (this.allName.indexOf(restwo.materialCode) == -1) {
              this.copyTable.push(restwo);
            }
          }
        }
      } else {
        toast(res.msg);
      }
      this.code = "";
    },
    //传回来把组件关闭
    Sure() {
      setTimeout(() => {
        this.ShowStatue = false;
      }, 100);
      this.newitem = "";
      this.stoDate.forEach((item) => {
        if (item.material == this.ShowData.productid) {
          this.newitem = item.item;
        }
      });
      this.getOther();
    },
    //主列表数据
    getOther() {
      this.detailData.push({
        UniqueId: this.ShowData.uniqueid,
        MATERIALSKU: this.ShowData.productid,
        Num: this.ShowData.stockquantity,
        SortCode: 1,
        Description: this.newitem,
      });
    },
    //获取当前的日期
    getNowDate() {
      let now = new Date();
      let year = now.getFullYear(); //年
      let month = now.getMonth() + 1; //月
      let day = now.getDate(); //日
      return `${year}-${month}-${day}`;
    },
    //提交
    async onSubmit() {
      if (this.rowData.length == 0) {
        this.$toast("当前表格为空");
      } else {
        this.noFitWuliao = [];
        this.copyTable.forEach((item) => {
          this.stoDate.forEach((itemtwo) => {
            if (item.materialCode == itemtwo.material) {
              if (Number(item.quantity) > Number(itemtwo.quantity)) {
                this.noFitWuliao.push(itemtwo.materialName);
              }
            }
          });
        });

        if (this.noFitWuliao[0] == null) {
          let type = "ReturnPicking";
          let submit = {
            BillType: "ReturnPicking",
            BillTypeName: "PO退货",
            OutTime: this.getNowDate(),
            CreatedId: JSON.parse(localStorage.getItem("userid")),
            CreatedName: JSON.parse(localStorage.getItem("username")),
            Plant: this.value,
            kczt: this.kc_value,
            Supplier: "",
            IsLastOut: false,
            SupplierId: "",
            BillNo: "",
            LinkNo: this.orderNum,
            WareHouseId: "0020",
            Num_Packing: "",
            WareHouseName: "0020",
            HandUserName: this.returnPerson,
          };
          let res = await InformationSubmit(
            type,
            JSON.stringify(submit),
            JSON.stringify(this.detailData)
          );
          if (res.d.state == "success") {
            this.rowData = [];
            this.detailData = [];
            this.value = "";
            this.orderNum = "";
            this.copyTable = [];
            this.kc_value = "";
            if (this.rowData.length == 0) {
              this.$toast({
                type: "success",
                message: "提交成功",
              });
            }
          } else {
            toast(res.d.message);
          }
        } else {
          this.ifShowNoFit = true;
        }
      }
    },
    //点击弹出修改数量弹窗
    updateNum() {
      this.selectDate = this.gridApi.getSelectedRows();
      if (this.selectDate[0] == null) {
        this.$toast("请选择要修改的数据");
      } else {
        this.ifShowUpdateNum = true;
      }
    },
    // 修改数量确认按钮
    SureUpdate() {
      if (this.needUpdateNum == "" || this.needUpdateNum == 0) {
        this.$toast("未输入数量无法修改");
        this.needUpdateNum = "";
      } else {
        let oldNum = this.selectDate[0].stockquantity;
        this.selectDate[0].stockquantity = this.needUpdateNum;
        this.gridApi.applyTransaction({ update: this.selectDate });
        this.detailData.forEach((item) => {
          if (this.selectDate[0].uniqueid == item.UniqueId) {
            item.Num = Number(this.needUpdateNum);
          }
        });
        this.needUpdateNum = "";

        let wlh = this.selectDate[0].productid; //获取选中的物料号
        let number = Number(oldNum) - Number(this.selectDate[0].stockquantity); //获取修改数量与原数量相比实际减去多少数量
        this.copyTable.forEach((item) => {
          if (item.materialCode == wlh) {
            item.quantity = item.quantity - number;
          }
        });
      }
    },
    // 关闭enter键
    closeEnter() {
      document.onkeydown = function (e) {
        //捕捉回车事件
        var ev = typeof event != "undefined" ? window.event : e;
        if (ev.keyCode == 13 || event.which == 13) {
          return false;
        }
      };
    },
  },
  mounted() {
    this.type = parseInt(this.$route.params.type);
    this.setTitle();
    this.closeEnter();
  },
};
</script>

<style lang="less" scoped>
.ag-theme-alpine .ag-root-wrapper {
  border-left-width: 0;
  border-right-width: 0;
}
.tip {
  text-align: center;
  margin-bottom: 1rem;
  padding: 1rem;
  height: 1rem;
}
</style>
